<template>
  <div class="publish-management">
    <div class="header">
      <h2>发布管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索发布内容或发布者"
          style="width: 200px; margin-right: 10px;"
          clearable
          @clear="fetchPublishList"
          @keydown.enter="fetchPublishList"
        >
          <template #append>
            <el-button :icon="Search" @click="fetchPublishList" />
          </template>
        </el-input>
        <el-button type="primary" @click="handleAddPublish">新增发布</el-button>
        <el-button type="success" @click="fetchPublishList" :loading="loading" style="margin-left: 10px;">刷新</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedPublishes.length === 0"
          style="margin-left: 10px;"
        >
          批量删除({{ selectedPublishes.length }})
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table
        :data="publishList"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="publish_id" label="发布ID" width="100" sortable />
        <el-table-column prop="author.name" label="发布者" width="120" />
        <el-table-column label="内容" show-overflow-tooltip>
          <template #default="scope">
            <div class="content-cell">{{ scope.row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column label="图片" width="120">
          <template #default="scope">
            <div v-if="scope.row.images && scope.row.images.length > 0" class="image-thumbnails">
              <div
                v-for="(image, index) in scope.row.images.slice(0, 3)"
                :key="index"
                class="thumbnail-placeholder"
              >
                <el-image
                  :src="image.fileurl"
                  class="thumbnail"
                  fit="cover"
                />
              </div>
              <div v-if="scope.row.images.length > 3" class="more-count">
                +{{ scope.row.images.length - 3 }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="统计数据" width="110">
          <template #default="scope">
            <div class="stats">
              <div class="stat-item">
                <el-icon :size="14"><Star /></el-icon>
                <span>{{ scope.row.like_count || 0 }}</span>
              </div>
              <div class="stat-item">
                <el-icon :size="14"><ChatLineSquare /></el-icon>
                <span>{{ scope.row.comment_count || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="可见性" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.is_public" type="success">公开</el-tag>
            <el-tag v-else type="info">私有</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="200" sortable />
        <el-table-column label="操作" width="360" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleManageComments(scope.row)">评论管理</el-button>
            <el-button size="small" @click="handleManageLikes(scope.row)">点赞管理</el-button>
            <el-button size="small" @click="handleViewDetails(scope.row)">详情</el-button>
            <el-button size="small" @click="handleEditPublish(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeletePublish(scope.row)"
              :loading="deletingPublishId === scope.row.publish_id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[50, 500, 1000]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 评论管理弹窗 -->
    <CommentManagementDialog 
      v-model="commentManagementVisible"
      :publish-data="currentPublishForManagement"
    />
    
    <!-- 点赞管理弹窗 -->
    <LikeManagementDialog 
      v-model="likeManagementVisible"
      :publish-data="currentPublishForManagement"
    />
    
    <!-- 编辑/新增发布弹窗 -->
    <EditPublishDialog
      v-model="editDialogVisible"
      :publish-data="editingPublishData"
      :is-edit-mode="!!editingPublishData"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Star, ChatLineSquare } from '@element-plus/icons-vue'
import CommentManagementDialog from '@/views/Console/PublishManagement/CommentManagementDialog.vue'
import LikeManagementDialog from '@/views/Console/PublishManagement/LikeManagementDialog.vue'
import EditPublishDialog from '@/views/Console/PublishManagement/EditPublishDialog.vue'
import {
  type Publish,
  getPublishList, 
  deletePublish, 
  getPublishById, 
  batchDeletePublish
} from '@/api/modules/publish'

const router = useRouter()

// 发布列表
const publishList = ref<Publish[]>([])

// 加载状态
const loading = ref(false)

// 删除发布时的加载状态
const deletingPublishId = ref<number | null>(null)

// 选中的发布
const selectedPublishes = ref<Publish[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 管理弹窗相关
const commentManagementVisible = ref(false)
const likeManagementVisible = ref(false)
const currentPublishForManagement = ref<Publish | null>(null)

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editingPublishData = ref<Publish | null>(null)

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchPublishList();
};

// 获取发布列表
const fetchPublishList = async () => {
  loading.value = true
  try {
    const response = await getPublishList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    
    publishList.value = response.data?.list || []
    pagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    console.error('获取发布列表失败:', error)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (val: Publish[]) => {
  selectedPublishes.value = val
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchPublishList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchPublishList()
}

// 处理查看详情
const handleViewDetails = (publish: Publish) => {
  router.push(`/publish-management/detail/${publish.publish_id}`)
}

// 处理评论管理
const handleManageComments = async (publish: Publish) => {
  try {
    // 获取发布详情
    const response = await getPublishById({ publish_id: publish.publish_id! })
    currentPublishForManagement.value = response.data || null
    commentManagementVisible.value = true
  } catch (error) {
    console.error('获取发布详情失败:', error)
  }
}

// 处理点赞管理
const handleManageLikes = async (publish: Publish) => {
  try {
    // 获取发布详情
    const response = await getPublishById({ publish_id: publish.publish_id! })
    currentPublishForManagement.value = response.data || null
    likeManagementVisible.value = true
  } catch (error) {
    console.error('获取发布详情失败:', error)
  }
}

// 处理新增发布
const handleAddPublish = () => {
  editingPublishData.value = null
  editDialogVisible.value = true
}

// 处理编辑发布
const handleEditPublish = (publish: Publish) => {
  editingPublishData.value = publish
  editDialogVisible.value = true
}

// 处理编辑成功
const handleEditSuccess = () => {
  editDialogVisible.value = false
  // 重新获取发布列表
  fetchPublishList()
}

// 处理删除发布
const handleDeletePublish = async (publish: Publish) => {
  ElMessageBox.confirm(
    `确定要删除这条发布内容吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!publish.publish_id) return
    
    deletingPublishId.value = publish.publish_id
    try {
      await deletePublish({ publish_id: publish.publish_id })
      ElMessage.success('删除成功')
      // 重新获取发布列表
      fetchPublishList()
    } catch (error) {
      console.error('删除发布失败:', error)
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    } finally {
      deletingPublishId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除发布
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedPublishes.value.length} 条发布内容吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const publishIds = selectedPublishes.value.map(p => p.publish_id!).filter(id => id !== undefined);
      if (publishIds.length === 0) {
        ElMessage.warning('请选择有效的发布内容进行删除');
        return;
      }
      
      // 批量删除发布内容（后端暂未实现此接口）
      const response = await batchDeletePublish({ publish_ids: publishIds });
      
      ElMessage.success(response?.msg);
      // 清空选中项
      selectedPublishes.value = [];
      // 重新获取发布列表
      await fetchPublishList();
    } catch (error) {
      console.error('批量删除发布失败:', error);
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 组件挂载时获取发布列表
onMounted(() => {
  fetchPublishList()
})
</script>

<style scoped>
.publish-management {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  height: calc(100% - 150px);
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.content-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-thumbnails {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.thumbnail {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.thumbnail-placeholder {
  position: relative;
  display: inline-block;
}

.thumbnail-placeholder::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
}

.more-count {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.stat-item .el-icon {
  margin-right: 5px;
  font-size: 14px;
}
</style>

<!-- 添加全局样式来解决图片预览的层级问题 -->
<style>
.viewer-container {
  z-index: 9999 !important;
}

.viewer-mask {
  z-index: 9998 !important;
  background-color: rgba(0, 0, 0, 0.8) !important;
}

/* 确保预览时遮罩层覆盖整个视口 */
.viewer-open .viewer-mask {
  position: fixed !important;
}
</style>